<script setup lang="ts">
import { getMemberProfileAPI, putMemberProfileAPI } from '@/services/profile'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { ProfileDetail, Gender } from '@/types/member'
import { useMemberStore } from '@/stores'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const memberStore = useMemberStore()

// 个人信息
// const profile = ref<ProfileDetail>() // 初始值是空的，即undefined
// 会对个人信息进行修改，需提供初始值（v-model会读取绑定的值，但undefined不是对象没有属性就更没有属性值了，会报错）
// const profile = ref<ProfileDetail>({} as ProfileDetail)
// 此时泛型的指定可以省略
const profile = ref({} as ProfileDetail & { countyCode?: string })
const getMemberProfile = async () => {
  const res = await getMemberProfileAPI()
  profile.value = res.result
}

onLoad(() => {
  getMemberProfile()
})

// 上传文件
const uploadFile = (url: string) => {
  uni.uploadFile({
    url: '/member/profile/avatar', // 后端接口地址
    name: 'file',
    filePath: url,
    success: (res) => {
      // 成功发送请求，根据后端返回结果判断上传是否成功
      if (res.statusCode === 200) {
        // 后端会将文件进行保存，并返回文件的存储地址(http://....jpg)
        const avatar = JSON.parse(res.data).result.avatar
        // 更新头像
        profile.value!.avatar = avatar
        // 更新全局状态中的头像(返回上一页‘我的’页面时会使用)
        memberStore.profile!.avatar = avatar
        uni.showToast({ title: '上传成功', icon: 'success' })
      } else {
        uni.showToast({ title: '出错了', icon: 'error' })
      }
    },
  })
}

// 点击修改头像
const onChangeAvatar = () => {
  /* #ifdef MP-WEIXIN */
  // 微信小程序调用调用拍照/选择图片/视频
  uni.chooseMedia({
    count: 1, // 可选择文件的数量
    mediaType: ['image'],
    success: (res) => {
      // 用户选择文件并点击确定之后：获取文件本地路径(http://...jpg)
      const tempFilePath = res.tempFiles[0]
      // 上传图片给后端
      uploadFile(String(tempFilePath))
    },
  })
  /* #endif */

  /* #ifdef APP-PLUS || H5 */
  // 网页、app调用拍照/选择图片
  uni.chooseImage({
    count: 1,
    success: (res: any) => {
      const tempFilePath = res.tempFiles[0] as File // 文件路径
      uploadFile(String(tempFilePath)) // 上传
    },
  })
  /* #endif */
}

// 修改性别
const onGenderChange: UniHelper.RadioGroupOnChange = (event) => {
  profile.value.gender = event.detail.value as Gender
}

// 修改生日
const onBirthdayChange: UniHelper.DatePickerOnChange = (event) => {
  profile.value.birthday = event.detail.value
}

// 修改地区
/* #ifdef MP-WEIXIN */
let code: [string, string, string] = ['', '', '']
const onRegionChange: UniHelper.RegionPickerOnChange = (event) => {
  // 供前端渲染
  profile.value.fullLocation = event.detail.value.join('') // ['省','市','区']数组拼接成字符串
  // 供后端存储
  code = event.detail.code! // ['省编码','市编码','区编码']数组
}
/* #endif */

// 选择地区
/*  #ifdef H5 || APP-PLUS */
const onDataPickerChange: UniHelper.UniDataPickerOnChange = (e) => {
  // 此组件已经处理好了前端展示，只需处理后端参数即可
  const [provinceCode, cityCode, countyCode] = e.detail.value.map((item: any) => item.value)
  code = [provinceCode, cityCode, countyCode]
  profile.value.countyCode = countyCode // 区编码，供选择器回显
}
/* #endif */

// 修改个人信息
const onSubmit = async () => {
  const { nickname, gender, birthday } = profile.value!
  const res = await putMemberProfileAPI({
    // nickname: profile.value!.nickname,
    // gender: profile.value!.gender,
    // birthday: profile.value!.birthday,
    nickname,
    gender,
    birthday,
    provinceCode: code[0],
    cityCode: code[1],
    countyCode: code[2],
  })
  // 更新全局状态中的昵称(返回上一页‘我的’页面时会使用)
  memberStore.profile!.nickname = res.result.nickname
  uni.showToast({ title: '保存成功', icon: 'success' })
  setTimeout(() => {
    uni.navigateBack()
  }, 500)
}
</script>

<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <view class="avatar-content" @tap="onChangeAvatar">
        <image class="image" :src="profile?.avatar" mode="aspectFill" />
        <text class="text">点击修改头像</text>
      </view>
    </view>
    <!-- 表单 -->
    <view class="form">
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">账号</text>
          <text class="account">账号名</text>
        </view>
        <view class="form-item">
          <text class="label">昵称</text>
          <input class="input" type="text" placeholder="请填写昵称" v-model="profile!.nickname" />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <radio-group @change="onGenderChange">
            <label class="radio">
              <radio value="男" color="#27ba9b" :checked="profile?.gender === '男'" />
              男
            </label>
            <label class="radio">
              <radio value="女" color="#27ba9b" :checked="profile?.gender === '女'" />
              女
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">生日</text>
          <picker
            class="picker"
            mode="date"
            start="1900-01-01"
            :end="new Date()"
            :value="profile?.birthday"
            @change="onBirthdayChange"
          >
            <view v-if="profile?.birthday">{{ profile?.birthday }}</view>
            <view class="placeholder" v-else>请选择日期</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">城市</text>
          <!-- <picker class="picker" mode="region" :value="['广东省', '广州市', '天河区']"> -->
          <!-- #ifdef MP-WEIXIN -->
          <picker
            class="picker"
            mode="region"
            :value="profile?.fullLocation?.split(' ')"
            @change="onRegionChange"
          >
            <view v-if="profile?.fullLocation">{{ profile?.fullLocation }}</view>
            <view class="placeholder" v-else>请选择城市</view>
          </picker>
          <!-- #endif -->
          <!-- #ifdef H5 || APP-PLUS -->
          <uni-data-picker
            placeholder="请选择地址"
            popup-title="请选择城市"
            collection="opendb-city-china"
            field="code as value, name as text"
            orderby="value asc"
            :step-searh="true"
            self-field="code"
            parent-field="parent_code"
            :clear-icon="false"
            @change="onDataPickerChange"
            v-model="profile.countyCode"
          >
          </uni-data-picker>
          <!-- #endif -->
        </view>
        <view class="form-item">
          <text class="label">职业</text>
          <input class="input" type="text" placeholder="请填写职业" :value="profile?.profession" />
        </view>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button" @tap="onSubmit">保 存</button>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
}
</style>
